import {protocol, Request, FilePathWithHeaders} from "electron";
import protocolConfig from "../../common/var/protocolConfigFunc";
import {exists, parsePath, writeFileFromNet, writeSpecialSiteFileFromNet} from "../../common/function/fileFunc";
import {parseURL} from "../../common/function/httpFunc";
import {MangaSite} from "../../common/class/MangaSite/MangaSite";

export function registerMangaCover() {
    const protocolPrefix = "akaba";
    protocol.registerFileProtocol(protocolPrefix, (request, callback) => {
        akabaProtocolHandler(request, callback)
            .catch((err) => {
                console.error(err);
            });
    }, (error) => {
        if (error) {
            console.error("Failed to register protocol");
        }
    });
}

async function akabaProtocolHandler(request: Request, callback: (param: string | FilePathWithHeaders) => void) {
    const url = request.url;
    const filePath = protocolConfig.akaba.getPath(url);
    const fileExists = await exists(filePath);
    if (!fileExists) {
        const pathObj = parseURL(url);
        const searchString = pathObj.search;
        const originURLMatch = searchString.match(/(^|\?|&)origin=([^&]+)/);
        if (originURLMatch) {
            const originURL = decodeURIComponent(originURLMatch[2]);
            const mangaSiteMatch = searchString.match(/(^|\?|&)site-id=([^&]+)/);
            if (mangaSiteMatch) {
                const siteId = mangaSiteMatch[2];
                await writeSpecialSiteFileFromNet(url, siteId as MangaSite.TSiteId, originURL, filePath, "binary");
            } else {
                await writeFileFromNet(originURL, filePath, "binary");
            }
        }
    }
    callback({
        path: filePath,
    });
}
